import Url from 'url-parse';
import prettier from 'prettier/standalone';
import options from '../../.prettierrc.cjs';
import prettierPlugins from 'prettier/plugins/postcss';

/**
 * 解析 `url` 参数
 */
export const URL_PARAMS = new Url(location.href, true).query;

/**
 * 自动格式化代码的函数
 */
export async function formatCSS(css: string) {
  return await prettier.format(css, { parser: 'scss', plugins: [prettierPlugins], ...options }).catch(() => {});
}

/**
 * rpx 转 px
 */
export function rpxToPx(css: string, scale: number) {
  return css.replace(/(-?\d*\.?\d+)rpx/g, (_, v) => {
    /**
     * 细分转换规则
     * 0rpx => 0
     * 750rpx => 100vw
     */
    switch (true) {
      case v === '0':
        return '0';
      case v === '750':
        return '100vw';
      default:
        return `${(parseFloat(v) / scale).toFixed(2)}px`;
    }
  });
}

/**
 * 阻止默认行为
 */
export function preventDefault(e: Event) {
  e.preventDefault();
}

/**
 * 判断是否为true，可能存在字符串版本的true
 */
export function isTrue(v: boolean | string | null | undefined) {
  return v === true || v === 'true';
}

/**
 * 过滤掉不含有 `px` 单位的样式块
 */
export function filterPxStyles(input: string) {
  const lines = input.split('\n');
  let output = '';
  let insideBlock = false;
  let currentBlock: string[] = [];
  let openBraces = 0;
  for (const line of lines) {
    const trimmedLine = line.trim();
    if (trimmedLine.endsWith('{')) {
      insideBlock = true;
      openBraces++;
      currentBlock.push(line);
    } else if (trimmedLine === '}') {
      openBraces--;
      if (openBraces === 0) {
        insideBlock = false;
        // 检查 currentBlock 中的任意行是否包含 px 单位
        if (currentBlock.some((l: string) => l.includes('px'))) {
          output += currentBlock.join('\n') + '\n' + line + '\n';
        }
        currentBlock = [];
      } else {
        currentBlock.push(line);
      }
    } else if (insideBlock) {
      // 只保留含有 px 单位的行
      if (trimmedLine.includes('px')) {
        currentBlock.push(line);
      }
    }
  }
  return output.trim();
}
